package com.fram.common.util.sms;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fram.common.canstant.ErrCode;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.PublicMethod;
import com.fram.common.util.json.JSONTools;

public class SendSms {

	private static Logger LOG = LoggerFactory.getLogger(SendSms.class);

	protected static final String ACCESS_KEY_ID = "LTAI4FyMeq3gS4mHbggt6eTD";
	protected static final String SECRET = "tGFEHF37bhtsmEw3ybrHcEEEmI1Thz";

	public static final String TEMPLATE_CODE_VERIFICATION_CODE = "SMS_189216120";
	public static final String HEAD = "数营科技";

	// public static void main(String[] args) {
	// // {\"code\":123125}
	// try {
	// sendSms("17784077887", HEAD, TEMPLATE_CODE_VERIFICATION_CODE,
	// "{\"code\":123125}");
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	/** 发送短信 **/
	public static void sendSms(String phone, String head, String templateCode, String paramJson) throws ProAffairException {
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, SECRET);
		IAcsClient client = new DefaultAcsClient(profile);

		CommonRequest request = new CommonRequest();
		request.setMethod(MethodType.POST);
		request.setDomain("dysmsapi.aliyuncs.com");
		request.setVersion("2017-05-25");
		request.setAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", phone);
		request.putQueryParameter("SignName", head);
		request.putQueryParameter("TemplateCode", templateCode);
		request.putQueryParameter("TemplateParam", paramJson);
		try {
			CommonResponse response = client.getCommonResponse(request);
			Map<String, Object> responseMap = JSONTools.convertJsonStrToMap(response.getData());
			if (responseMap == null) {
				LOG.error("-短信-phone:{}-templateCode:{}-paramJson:{}-发送失败：{}", phone, templateCode, paramJson, response.getData());
				throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), "短信发送失败");
			}
			if (!("OK".equals(responseMap.get("Code")) && "OK".equals(responseMap.get("Message")))) {
				LOG.error("-短信-phone:{}-templateCode:{}-paramJson:{}-发送失败：{}", phone, templateCode, paramJson, response.getData());
				throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "短信发送失败");
			}
		} catch (Exception e) {
			LOG.error("-短信-phone:{}-templateCode:{}-paramJson:{}-发送异常：{}", phone, templateCode, paramJson, PublicMethod.printErrorTrace(e));
			throw new ProRunTimeException(ErrCode.ERR.getReturnCode(), "短信发送异常");
		}
	}
}